<script setup>
import {
  onMounted,
  onUnmounted,
  onBeforeUnmount,
  ref,
  watch,
  nextTick,
  computed,
} from "vue";
import * as echarts from "echarts";
import { useScaleStore } from "@/stores/scaleStore";

const props = defineProps({
  title: {
    type: String,
    default: "内波断面图",
  },
  gridData: {
    type: Array,
    default: () => [],
  },
  roadPath: {
    type: Array,
    default: () => [],
  },
  additionalInfo: {
    type: String,
    default: "",
  },
  closeEvent: Function,
  dataType: {
    type: String,
    default: "salinity",
    validator: (value) => ["salinity", "temperature"].includes(value),
  },
});

const closeClick = () => {
  props?.closeEvent();
};

let profileChart = null;
let resizeObserver = null;
const chartDom = ref(null);
const boxWrapRef = ref(null);
const headerRef = ref(null);
const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0 });
const currentPos = ref({ x: 0, y: 0 });
const currentScale = ref(1); // 当前窗口缩放比例
const isResizing = ref(false);
const resizeDirection = ref(null);
const startSize = ref({ width: 650, height: 580 });
const currentSize = ref({ width: 650, height: 580 });

const scaleStore = useScaleStore();

// 监听scaleStore的变化
watch(
  () => scaleStore.currentScale,
  (newScale) => {
    currentScale.value = newScale || 1;
  },
  { immediate: true }
);

// 颜色配置
const colorSchemes = {
  1: {
    colors: [
      "#313695", // 深蓝（最低温）
      "#4575b4",
      "#74add1",
      "#abd9e9",
      "#e0f3f8",
      "#ffffbf",
      "#fee090",
      "#fdae61",
      "#f46d43",
      "#d73027", // 红（最高温）
    ],
    unit: "°C",
    visualMapText: ["高温", "低温"], // 反转标注
    min: null, // 改为动态获取
    max: null, // 改为动态获取
  },
  2: {
    colors: [
      "#f7fbff", // 极浅蓝（低盐度）
      "#deebf7",
      "#c6dbef",
      "#9ecae1",
      "#6baed6",
      "#4292c6",
      "#2171b5",
      "#08519c",
      "#08306b", // 极深蓝（高盐度）
    ],
    unit: "PSU",
    visualMapText: ["高盐度", "低盐度"],
    min: 0,
    max: 40,
  },
};

const currentScheme = computed(() => colorSchemes[props.dataType]);

watch(
  () => [props.gridData, props.dataType],
  () => {
    if (props.gridData?.length) {
      renderProfile();
    }
  },
  { immediate: true, deep: true }
);

const handleMouseDown = (e) => {
  // 检查是否是缩放区域
  if (e.target.classList.contains("resize-handle")) {
    isResizing.value = true;
    resizeDirection.value = e.target.dataset.direction;
    startSize.value = { ...currentSize.value };
    startPos.value = { x: e.clientX, y: e.clientY };

    e.stopPropagation();
    e.preventDefault();
    document.addEventListener("mousemove", handleResizeMove);
    document.addEventListener("mouseup", handleResizeEnd);
    return;
  }

  // 原有拖动逻辑
  if (!headerRef.value || !headerRef.value.contains(e.target)) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  isDragging.value = true;
  startPos.value = {
    x: adjustedX - currentPos.value.x,
    y: adjustedY - currentPos.value.y,
  };

  e.stopPropagation();
  e.preventDefault();

  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", handleMouseUp);
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  const newX = adjustedX - startPos.value.x;
  const newY = adjustedY - startPos.value.y;

  currentPos.value = { x: newX, y: newY };

  if (boxWrapRef.value) {
    boxWrapRef.value.style.left = `${newX}px`;
    boxWrapRef.value.style.top = `${newY}px`;
  }

  e.preventDefault();
};

const handleMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
};

const handleResizeMove = (e) => {
  if (!isResizing.value) return;

  const deltaX = (e.clientX - startPos.value.x) / currentScale.value;
  const deltaY = (e.clientY - startPos.value.y) / currentScale.value;

  const newSize = { ...currentSize.value };

  switch (resizeDirection.value) {
    case "e":
      newSize.width = Math.max(500, startSize.value.width + deltaX);
      break;
    case "s":
      newSize.height = Math.max(400, startSize.value.height + deltaY);
      break;
    case "se":
      newSize.width = Math.max(500, startSize.value.width + deltaX);
      newSize.height = Math.max(400, startSize.value.height + deltaY);
      break;
  }

  currentSize.value = newSize;
  updateChartSize();
  e.preventDefault();
};

const handleResizeEnd = () => {
  isResizing.value = false;
  resizeDirection.value = null;
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
};

const updateChartSize = () => {
  if (profileChart) {
    profileChart.resize();
  }
};

async function initChart() {
  await nextTick();
  if (!chartDom.value) return;

  profileChart = echarts.init(chartDom.value);

  if (boxWrapRef.value) {
    const rect = boxWrapRef.value.getBoundingClientRect();
    currentPos.value = { x: rect.left, y: rect.top };
  }

  if (props.gridData?.length) {
    renderProfile();
  }
}

function processGridData() {
  if (!props.gridData?.length || !props.roadPath?.length) {
    return { heatmapData: [], yAxisData: [], xAxisLabels: [] };
  }

  const heatmapData = [];
  const yAxisData = [];
  const xAxisLabels = [];

  // 获取起点和终点坐标
  const pointA = props.roadPath[0];
  const pointB = props.roadPath[props.roadPath.length - 1];

  // 处理每个深度分层
  props.gridData.forEach((depthLayer, depthIndex) => {
    const depthKey = Object.keys(depthLayer)[0];
    const points = depthLayer[depthKey];

    // 计算该分层的平均深度（取绝对值）
    const validDepths = points
      .filter((point) => point?.high !== undefined && point?.high !== null)
      .map((point) => Math.abs(point.high));

    const avgDepth =
      validDepths.length > 0
        ? (
            validDepths.reduce((sum, depth) => sum + depth, 0) /
            validDepths.length
          ).toFixed(0)
        : "0";

    yAxisData.push(`${avgDepth}m`);

    // 处理该分层内的每个点
    points.forEach((point, pointIdx) => {
      // 跳过无效数据点
      if (
        point?.high === undefined ||
        point?.high === null ||
        point?.value === undefined ||
        point?.value === null
      ) {
        return;
      }

      // 计算当前点的经纬度（线性插值）
      const ratio = pointIdx / (points.length - 1);
      const longitude =
        pointA.longitude + (pointB.longitude - pointA.longitude) * ratio;
      const latitude =
        pointA.latitude + (pointB.latitude - pointA.latitude) * ratio;

      // 只在第一层收集x轴标签（避免重复）
      if (depthIndex === 0 && pointIdx % 3 === 0) {
        // 调整为每3个点显示一个标签
        xAxisLabels.push(`${longitude.toFixed(2)}°E/${latitude.toFixed(2)}°N`); // 简化显示
      }

      // 热力图数据格式: [xIndex, yIndex, value]
      heatmapData.push([pointIdx, depthIndex, point.value]);
    });
  });

  return { heatmapData, yAxisData, xAxisLabels };
}

function calculateValueRange(heatmapData) {
  // 提取所有有效值
  const allValues = heatmapData.map((item) => item[2]);

  if (!allValues.length) {
    return {
      min: props.dataType === 1 ? 10 : 0,
      max: props.dataType === 1 ? 30 : 40,
    };
  }

  // 计算实际数据范围
  const dataMin = Math.min(...allValues);
  const dataMax = Math.max(...allValues);
  return {
    min: dataMin,
    max: dataMax,
  };
}

function renderProfile() {
  if (!profileChart || !props.gridData?.length || !props.roadPath?.length) {
    return;
  }

  try {
    // 1. 处理数据
    const { heatmapData, yAxisData, xAxisLabels } = processGridData();

    // 2. 计算值范围
    const { min: minValue, max: maxValue } = calculateValueRange(heatmapData);

    // 3. 配置ECharts选项（优化了grid和布局）
    const option = {
      title: {
        text:
          props.title || (props.dataType === 1 ? "温度断面图" : "盐度断面图"),
        left: "center",
        textStyle: {
          color: "#38e1ff",
          fontSize: 20,
          fontWeight: "bold",
        },
      },
      tooltip: {
        position: "top",
        formatter: function (params) {
          const data = params.data;
          return `${props.dataType === 1 ? "温度" : "盐度"}: ${data[2].toFixed(
            2
          )} ${currentScheme.value.unit}<br>深度: ${yAxisData[params.data[1]]}`;
        },
      },
      grid: {
        left: "3%",
        right: "6%", // 进一步减少右侧空间
        bottom: "5%", // 进一步减少底部空间
        top: "12%", // 进一步减少顶部空间
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: xAxisLabels,
        name: "经纬度",
        nameLocation: "middle",
        nameGap: 15,
        axisLabel: {
          color: "#8eb9ff",
          fontSize: 10, // 更小的字体
          rotate: 30, // 减小旋转角度
          interval: 0, // 强制显示所有标签
          formatter: function (value) {
            return value.replace("/", "\n"); // 换行显示经纬度
          },
        },
        axisLine: {
          lineStyle: {
            color: "#4c9bfd",
            width: 1, // 更细的轴线
          },
        },
      },
      yAxis: {
        type: "category",
        data: yAxisData,
        name: "深度(m)",
        inverse: true,
        nameGap: 10,
        axisLine: {
          lineStyle: {
            color: "#4c9bfd",
            width: 1, // 更细的轴线
          },
        },
        axisLabel: {
          color: "#8eb9ff",
          fontSize: 10, // 更小的字体
          margin: 5, // 更小的边距
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "rgba(76, 155, 253, 0.2)",
            type: "dashed",
          },
        },
      },
      visualMap: {
        min: minValue,
        max: maxValue,
        calculable: true,
        orient: "vertical",
        right: "1%",
        top: "middle",
        text: currentScheme.value.visualMapText,
        textStyle: {
          color: "#fff",
        },
        inRange: {
          color: currentScheme.value.colors,
        },
        precision: 2,
        inverse: props.dataType === 1,
        itemWidth: 20, // 更窄的图例
        itemHeight: 300, // 更长的图例
      },
      series: [
        {
          name: props.dataType === 1 ? "温度" : "盐度",
          type: "heatmap",
          data: heatmapData,
          encode: {
            x: 0,
            y: 1,
          },
          itemStyle: {
            borderWidth: 0,
            opacity: 0.9,
          },
          emphasis: {
            itemStyle: {
              borderWidth: 1,
              borderColor: "rgba(255,255,255,0.8)",
              shadowBlur: 10,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
          progressive: 1000,
          label: {
            show: false,
          },
        },
      ],
    };

    profileChart.setOption(option, true);
    profileChart.resize();
  } catch (error) {
    console.error("渲染图表时出错:", error);
  }
}

onMounted(async () => {
  await initChart();

  resizeObserver = new ResizeObserver(() => {
    if (profileChart) {
      profileChart.resize();
    }
  });

  if (chartDom.value) {
    resizeObserver.observe(chartDom.value);
  }
});

onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
  }

  if (profileChart) {
    const dom = profileChart.getDom();
    if (dom) {
      const canvas = dom.querySelector("canvas");
      if (canvas) {
        const gl =
          canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
        if (gl) {
          const loseContext = gl.getExtension("WEBGL_lose_context");
          if (loseContext) loseContext.loseContext();
        }
      }
    }
    profileChart.dispose();
    profileChart = null;
  }

  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
});
</script>

<template>
  <div
    class="popup-container"
    :style="{
      left: `${currentPos.x}px`,
      top: `${currentPos.y}px`,
      width: `${currentSize.width}px`,
      height: `${currentSize.height}px`,
    }"
  >
    <div class="pine"></div>
    <div class="box-wrap" ref="boxWrapRef">
      <!-- 标题栏区域 -->
      <div class="header-area" ref="headerRef" @mousedown="handleMouseDown">
        <div class="title-text">{{ title }}</div>
        <div class="close" @click="closeClick">X</div>
      </div>
      <!-- 图表区域 -->
      <div ref="chartDom" class="chart-container"></div>

      <!-- 缩放控制手柄 -->
      <div
        class="resize-handle resize-e"
        data-direction="e"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-s"
        data-direction="s"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-se"
        data-direction="se"
        @mousedown="handleMouseDown"
      ></div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.popup-container {
  position: fixed;
  z-index: 9999;
  cursor: default;
  min-width: 500px;
  min-height: 400px;
}

.box-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10px;
  border: 1px solid #38e1ff;
  background-color: rgba(30, 80, 120, 0.7);
  box-shadow: 0 0 10px 2px #29baf1;
  animation: slide 1s;
  overflow: hidden;
  user-select: none;
}

/* 标题栏样式 */
.header-area {
  position: relative;
  height: 40px;
  background: linear-gradient(
    to right,
    rgba(20, 60, 100, 0.9),
    rgba(30, 80, 120, 0.9)
  );
  border-bottom: 1px solid #38e1ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  cursor: grab;

  &:active {
    cursor: grabbing;
  }
}

.title-text {
  color: #38e1ff;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(56, 225, 255, 0.7);
}

.close {
  color: #fff;
  text-shadow: 2px 2px 2px #022122;
  cursor: pointer;
  font-size: 20px;
  transition: all 0.2s;

  &:hover {
    color: #ff6b6b;
    transform: scale(1.1);
  }
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: calc(100% - 40px); /* 减去标题栏高度 */
  padding: 10px;
  box-sizing: border-box;
}

/* 缩放控制手柄样式 */
.resize-handle {
  position: absolute;
  background: transparent;
  z-index: 10;
}

.resize-e {
  cursor: e-resize;
  width: 10px;
  height: 100%;
  right: 0;
  top: 0;
}

.resize-s {
  cursor: s-resize;
  width: 100%;
  height: 10px;
  bottom: 0;
  left: 0;
}

.resize-se {
  cursor: se-resize;
  width: 15px;
  height: 15px;
  right: 0;
  bottom: 0;
  background: #38e1ff;
  opacity: 0;
  transition: opacity 0.2s;
}

.box-wrap:hover .resize-se {
  opacity: 0.8;
}

@keyframes slide {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.pine {
  position: absolute;
  width: 100px;
  height: 100px;
  box-sizing: border-box;
  line-height: 120px;
  text-indent: 5px;
}

@keyframes fontColor {
  0% {
    color: #ffffff00;
    text-shadow: 1px 1px 5px #00252000;
  }
  40% {
    color: #ffffff00;
    text-shadow: 1px 1px 5px #00252000;
  }
  100% {
    color: #ffffff;
    text-shadow: 1px 1px 5px #002520d2;
  }
}
</style>
